const OpenAI = require('openai')

const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: process.env.DEEPSEEK_API_KEY
})

const deepseekService = {
  /**
   * 处理多轮对话
   * @param {Array|string} messages - 对话历史消息数组或单条消息
   * @param {Object} options - 配置选项
   * @returns {Promise} 返回AI响应
   */
  async chatCompletion(messages, options = {}) {
    try {
      // 验证和格式化消息
      let formattedMessages = []

      if (typeof messages === 'string') {
        // 如果传入的是字符串，转换为消息数组
        formattedMessages = [{ role: "user", content: messages }]
      } else if (Array.isArray(messages)) {
        // 验证消息数组格式
        formattedMessages = messages.map(msg => {
          if (!msg.role || !msg.content) {
            throw new Error('Invalid message format: each message must have role and content')
          }
          return {
            role: msg.role,
            content: msg.content
          }
        })
      } else {
        throw new Error('Messages must be a string or an array')
      }

      // 添加系统消息（如果不存在）
      if (!formattedMessages.some(msg => msg.role === 'system')) {
        formattedMessages.unshift({
          role: "system",
          content: "You are a helpful assistant."
        })
      }

      // 构建请求配置
      const requestConfig = {
        messages: formattedMessages,
        model: options.model || "deepseek-chat",
        temperature: options.temperature || 0.7,
        max_tokens: options.max_tokens || 2000,
      }

      console.log('Sending request to DeepSeek API:', {
        ...requestConfig,
        apiKey: '***' // 隐藏 API key
      })

      const completion = await openai.chat.completions.create(requestConfig)

      // 验证响应数据
      if (!completion || !completion.choices || !completion.choices[0]) {
        throw new Error('Invalid response from DeepSeek API')
      }

      return {
        success: true,
        data: {
          choices: [{
            message: completion.choices[0].message
          }]
        }
      }

    } catch (error) {
      console.error('[DeepSeek Error]:', error)

      // 细化错误处理
      let errorMessage = 'AI 服务调用失败'
      if (error.response) {
        // API 错误响应
        errorMessage = `API Error: ${error.response.status} - ${error.response.data?.error?.message || error.message}`
      } else if (error.request) {
        // 网络错误
        errorMessage = '网络请求失败，请检查网络连接'
      } else {
        // 其他错误
        errorMessage = error.message || errorMessage
      }

      return {
        success: false,
        error: errorMessage,
        details: error.response?.data || error.message
      }
    }
  },

  /**
   * 简单的单轮对话（向后兼容）
   */
  async simpleChatCompletion(prompt) {
    try {
      const response = await this.chatCompletion([
        { role: "user", content: prompt }
      ])

      if (!response.success) {
        throw new Error(response.error)
      }

      return response.data.choices[0].message.content
    } catch (error) {
      console.error('[DeepSeek Simple Chat Error]:', error)
      throw new Error(error.message || '调用 AI 服务失败')
    }
  }
}

module.exports = { deepseekService }
